using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json.Linq;

namespace JsonRpcGen.TypeHandler
{
    internal class MultiTypeHandler :TypeHandler
    {
        private readonly JToken _types;

        public MultiTypeHandler(JToken types)
        {
            _types = types;
        }

        public override void Write(StreamWriter writer, string namesp, string className, Dictionary<string, string> replacements)
        {
            writer.WriteLine("namespace " + namesp);
            writer.WriteLine("{");
            int counter = 1;
            var classNameFull = namesp.Replace(Global.BaseNamespace + ".", "") + "." +
                                className;
            bool handleBaseAsInterface=false;

            foreach (var type in _types)
            {
                var refType = type["$ref"];
                if (refType != null)
                {
                    handleBaseAsInterface = true;
                    var typeHandler = new ObjectTypeHandler(new JArray(), refType.ToString() + ", " + classNameFull);
                    typeHandler.WriteClass(writer, className + counter, replacements);
                }
                else
                {
                    var enums = type["enums"];
                    if (enums != null) 
                    {
                        var typeHandler = new EnumTypeHandler(enums);
                        typeHandler.WriteEnum(writer, className + counter);
                    }
                    else
                    {
                        var typeHandler = new ObjectTypeHandler(type["properties"], classNameFull);
                        typeHandler.WriteClass(writer, className + counter, replacements);
                    }
                }
                
                counter++;
            }

            writer.Write("   public ");
            if (handleBaseAsInterface)
            {
                writer.Write("interface");
            }
            else
            {
                writer.Write("class");
            }
            writer.WriteLine(" " + className);
            writer.WriteLine("   {");
            writer.WriteLine("   }");
           
            writer.WriteLine("}");
        }
    }
}